<template>
    <!-- 权限信息 -->
    <div class="box">
        <div>
            <a-row>
                <a-col :span="12" class="inp">
                    <a-form-item label="名字" class="inp_item">
                        <a-input v-model:value="search_info" placeholder="请输入" />
                    </a-form-item>
                </a-col>
                <a-col :span="12" class="pluss">
                    <div class="pluss_item" @click="reset">
                        <span>重置</span>
                    </div>
                    <div class="pluss_item" @click="search">
                        <SearchOutlined />
                        <span>查询</span>
                    </div>
                    <div class="pluss_item" @click="poput('')">
                        <PlusOutlined />
                        <span>新建</span>
                    </div>
                </a-col>
            </a-row>
        </div>
        <div>
            <a-table :data-source="data" :columns="columns" :pagination="false">
                <template #name="{ text, record }">
                    <div class="editable-cell">
                        <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                            <a-input v-model:value="editableData[record.key].name" @pressEnter="save(record.key)" />
                            <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
                        </div>
                        <div v-else class="editable-cell-text-wrapper">
                            {{ text || ' ' }}
                            <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
                        </div>
                    </div>
                </template>
                <template #operation="{ record }" v-slot:bodyCell="{columns,record}">
                    <FormOutlined class="revise_info" @click="revise(record)" />
                    <a-popconfirm v-if="data.length" title="是否删除?" @confirm="onDelete(record.key)">
                        <DeleteOutlined class="del_info" />
                    </a-popconfirm>
                </template>
            </a-table>
            <div class="pagination">
                <a-pagination :pageSize="5" :total="total" @change="paginat" />
            </div>
        </div>
        <a-modal v-model:open="open" title="编辑" @ok="poput" :afterClose="close">
            <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-form-item label="用户名" v-bind="validateInfos.name">
                    <a-input v-model:value="modelRef.name" placeholder="请输入" />
                </a-form-item>
                <a-form-item label="简介" v-bind="validateInfos.name">
                    <a-textarea v-model:value="modelRef.brief" placeholder="请输入" allow-clear />
                </a-form-item>
                <!-- 头像 -->
                <a-form-item label="头像">
                    <a-upload v-model:file-list="fileList" name="file" list-type="picture-card" class="avatar-uploader"
                        :show-upload-list="false" :action="serverUrl + '/common/upload'" :before-upload="beforeUpload"
                        @change="handleChange">
                        <img class="file_img" v-if="imageUrl" :src="imageUrl" alt="头像图片" />
                        <div v-else>
                            <loading-outlined v-if="loading"></loading-outlined>
                            <plus-outlined v-else></plus-outlined>
                            <div class="ant-upload-text">Upload</div>
                        </div>
                    </a-upload>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>
<script setup>

import { ref, h, reactive, computed } from 'vue';
import { get, post, patch, del, serverUrl, dalImg } from '../../utils/request'
import { Form, message } from 'ant-design-vue';
import { LoadingOutlined, SearchOutlined, PlusOutlined, CheckOutlined, EditOutlined, FormOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { cloneDeep } from 'lodash-es';
const columns = [
    {
        title: '序号',
        dataIndex: 'id',
        key: 'id',
        align: 'center'
    },
    {
        title: '名字',
        dataIndex: 'name',
        key: 'name',
        align: 'center'
    },
    {
        title: '头像',
        dataIndex: 'logo',
        key: 'avatar',
        customRender: ({ value }) => {
            return h(
                'img',
                {
                    src: value,
                    style: 'height: 50px;'
                },
            );
        },
        align: 'center'
    },
    {
        title: '描述',
        dataIndex: 'describe',
        key: 'describe',
        ellipsis: true,
        align: 'center'
    },
    {
        title: '操作',
        dataIndex: 'operation',
        key: 'address 4',
        ellipsis: true,
        align: 'center',
        slots: {
            customRender: 'operation',
        },

    },
];
const data = ref([])
const modifyEdits_id = ref('') // 判断修改还还是添加  空 为添加
const open = ref(false);
const arr_data = ref([])
const total = ref()
const useForm = Form.useForm;

const managers = async (page = 1) => {
    const managers = await get('/admin/doctor_titles', { per: 5, page })
    data.value = []

    arr_data.value = managers.data.list
    managers.data.list.forEach((item, index) => {
        data.value.push({
            key: item.id,
            id: index + 1 + '',
            name: item.name,
            logo: dalImg(serverUrl + item.image),
            describe: item.desc,
        })
    });
    total.value = managers.data.total

}
managers()
const poput = async () => {
    open.value = !open.value
    if (!open.value) {  // 添加删除
        const { name, brief } = modelRef.value
        const addmanager = {
            "name": name,
            "desc": brief,
            "image": avatar_url.value,
        }
        if (modifyEdits_id.value != '') {
            addmanager.image = avatar_url.value.split(serverUrl).pop()
            patch('/admin/doctor_titles/' + modifyEdits_id.value, addmanager).then(res => {
                modifyEdits_id.value = ''
                message.success('修改成功')
                managers()
            }).catch(err => {
                message.error('修改失败,服务器错误')
            })
        } else {
            post('/admin/doctor_titles', addmanager).then(res => {
                data.value = []
                message.success('添加成功')
                managers()
                modelRef.value = {
                    name: '',
                    brief: ''
                }
            }).catch(err => {
                message.error('添加失败,服务器错误')
            })
        }
    }
}

const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref('');
const avatar_url = ref('')
const handleChange = info => {
    if (info.file.status === 'uploading') {
        loading.value = true;
        return;
    }
    if (info.file.status === 'done') {
        //    从现实世界中的响应中获取此 URL。
        avatar_url.value = info.file.response.data
        getBase64(info.file.originFileObj, base64Url => {
            imageUrl.value = base64Url;
            loading.value = false;
        });
    }
    if (info.file.status === 'error') {
        loading.value = false;
        message.error('上传错误');
    }
};
const beforeUpload = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('您只能上传JPG文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片必须小于 2MB！');
    }
    return isJpgOrPng && isLt2M;
};
function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}


// 关闭对话框回调
const close = () => {
    modelRef.value = {
        name: '',
        brief: ''
    }
    modifyEdits_id.value = ''
}

const editableData = reactive({});
const edit = key => {
    editableData[key] = cloneDeep(data.value.filter(item => key === item.key)[0]);
};

// 删除
const save = key => {
    Object.assign(data.value.filter(item => key === item.key)[0], editableData[key]);
    delete editableData[key];
};
const onDelete = key => {
    del('/admin/doctor_titles/' + key).then(res => {
        message.success('删除成功')
    }).catch(err => {
        message.error('删除失败,服务器错误')
    })
    data.value = data.value.filter(item => item.key !== key);
};

// 修改
const revise = record => {
    open.value = !open.value
    modelRef.value = {
        name: record.name,
        brief: record.describe
    };
    avatar_url.value = record.logo
    imageUrl.value = record.logo
    modifyEdits_id.value = record.key
}
// 表单
const modelRef = ref({
    name: '',
    brief: ''
});

const { validateInfos } = useForm(
    modelRef,
    reactive({
        name: [
            {
                required: true,
                message: '请输入',
            },
        ],
        brief: [
            {
                required: true,
                message: '请输入',
            },
        ],
    }),
);

const labelCol = { span: 4 }
const wrapperCol = { span: 14 }


// 分页
const paginat = (page) => {
    managers(page)
}
// 搜索
const search_info = ref('') // 用户
const search = () => {
    if (search_info.value.trim() == '') {
        message.info('请选择搜索参数')
    }
    const data_arr = arr_data.value.filter(item => {
        if (item.name == search_info.value) {
            return item
        }
    })
    data.value = []
    data_arr.forEach((item, index) => {
        data.value.push({
            key: item.id,
            id: index + 1 + '',
            name: item.name,
            logo: dalImg(serverUrl + item.image),
            describe: item.desc,
        })
    });

}
// 重置
const reset = () => {
    location.reload()
}
</script>
<style scoped>
.box {
    height: 100%;
    overflow-y: auto;
}

.inp {
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.inp_item {
    flex: 1;
    padding: 0 5px;
}

.operate_but {
    display: flex;
    justify-content: center;
    align-items: center;
}

.operate_but .but1 {
    width: 60px;
    height: 20px;
}

:where(.css-dev-only-do-not-override-185kyl0).ant-col-8 {
    padding: 12px;
}

.file_img {
    width: 100%
}

.pagination {
    width: 100%;
    text-align: end;
    padding-top: 10px;
    box-sizing: border-box;
}

.pluss {
    display: flex;
    justify-content: end;
    align-items: center;
}

.pluss_item {
    width: 90px;
    height: 30px;
    background-color: #1890ff;
    text-align: center;
    line-height: 30px;
    margin-bottom: 20px;
    color: #fff;
    cursor: pointer;
}

.pluss .pluss_item:nth-child(1) {
    background-color: #fff;
    border: 1px solid #d9d9d9;
    color: #000;
}

.pluss .pluss_item:nth-child(2) {
    margin-left: 10px;
    margin-right: 10px;
}

.del_info,
.anticon {
    width: 30px;
    height: 30px;
    display: inline-block;
    text-align: center;
    line-height: 30px;
}

.del_info {
    margin: 0 10px;
    background-color: red !important;
    color: #fff !important;
}

.anticon[data-v-4e879eca]:nth-child(3) {
    background-color: #fff;
    color: #000;
    border: 1px solid #d9d9d9;
}

.revise_info {
    border: 1px solid #d9d9d9;
    background-color: #1890ff;
    color: #fff;
}
</style>